package com.jpxx.netty.marshalling;

import java.io.File;
import java.io.FileInputStream;

import com.jpxx.netty.util.GZipUtilsOK;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client {  

	static final String HOST = System.getProperty("host", "127.0.0.1");  
	static final int PORT = Integer.parseInt(System.getProperty("port", "8765"));  
	static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));  

	public static void main(String[] args) throws Exception {  
		// Configure the client.  
		EventLoopGroup group = new NioEventLoopGroup();  
		try {  
			Bootstrap b = new Bootstrap();
			b.group(group)  
			.channel(NioSocketChannel.class)  
			.option(ChannelOption.TCP_NODELAY, true)  
			.handler(new ChannelInitializer<SocketChannel>() {  
				@Override  
				public void initChannel(SocketChannel sc) throws Exception {  
					 sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());  
		             sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());  
		             sc.pipeline().addLast(new ClientHandler());  
				}  
			});  

			ChannelFuture future = b.connect(HOST, PORT).sync(); //绑定服务端
			
			for(int i=1;i<=5;i++){  
	            Req req = new Req();  
	            req.setId(i);  
	            req.setRequestMessage("client发送的数据:"+i);
	            req.setName("name"+i);  
	            
	            //读取文件 并压缩成字节发送到客户端
	            String readPath = System.getProperty("user.dir")+File.separatorChar+"sources"+File.separatorChar+"00"+i+".jpg";
	        	File file = new File(readPath);
	        	FileInputStream fis = new FileInputStream(file);
	        	byte[] data = new byte[fis.available()];
	        	fis.read(data);
	        	fis.close();
	        	req.setAttachment(GZipUtilsOK.compress(data));//压缩
	            
	            future.channel().writeAndFlush(req);//client  to  server
	        }  
			
			future.channel().closeFuture().sync();  
		} finally {  
			group.shutdownGracefully();  
		}  
	}  

}  